#!/usr/bin/perl

$|=1;
print("Content-Type: application/octet-stream\r\n\r\n");

$target = <>;
$target =~ s/\r?\n$//;
$pidFile = "/tmp/ChopSet_$target";

if($target =~ m/^all$/i){
	$num = 0;
	if(opendir(DIR, "/tmp")){
		while($file = readdir(DIR)){
			if($file =~ m/^ChopSet_/){
				$num++ if(&killFromPidFile("/tmp/$file"));
			}
		}
		closedir(DIR);
	}
	print("success.\n$num processes killed.\n");
}else{
	if(&killFromPidFile("/tmp/ChopSet_$target")){
		print("success.\n");
	}else{
		print("failed.\n");
	}
}
exit(0);

sub killFromPidFile{
	my($pidFile) = @_;
	return 0 unless(open(PIDFILE, $pidFile));
	my($pid) = <PIDFILE>;
	close(PIDFILE);
	unlink($pidFile);
	if($pid > 0 && kill(10, $pid) == 1){ # sig USER1
		return 1;
	}else{
		return 0;
	}
	return 0;
}
